package com.yn.service.zy.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.beust.jcommander.internal.Lists;
import com.yn.common.enums.AuditStatusEnum;
import com.yn.common.enums.BooleanEnum;
import com.yn.common.exception.TransitException;
import com.yn.common.model.user.User;
import com.yn.common.model.zy.TCarManageDO;
import com.yn.common.model.zy.TCareforInfoDO;
import com.yn.common.page.BasePage;
import com.yn.common.request.driver.CareforRequest;
import com.yn.common.request.sc.CarManageRequest;
import com.yn.service.dao.zy.TCareforInfoMapper;
import com.yn.service.service.UserService;
import com.yn.service.zy.TCarFleetManageService;
import com.yn.service.zy.TCareforInfoService;
import com.yn.service.zy.model.query.TCareforInfoQuery;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;


@Service
@Slf4j
public class TCareforInfoServiceImpl extends ServiceImpl<TCareforInfoMapper, TCareforInfoDO> implements TCareforInfoService {

    @Resource
    private TCareforInfoMapper tCareforInfoMapper;

    @Resource
    private TCarFleetManageService tCarFleetManageService;

    @Resource
    private UserService userService;

    /**
     * 分页获取陪护相关接口
     * @param query
     * @param basePage
     * @return
     */
    @Override
    public IPage<TCareforInfoDO> listPage(TCareforInfoQuery query, BasePage basePage) {
        IPage<TCareforInfoDO> page = new Page<>(basePage.getPage(),basePage.getLimit());

        LambdaQueryWrapper<TCareforInfoDO> queryWrapper = Wrappers.lambdaQuery();

        if (!ObjectUtils.isEmpty(query)) {
            queryWrapper.like(StringUtils.isNotBlank(query.getCarefoProject()),TCareforInfoDO::getCarefoProject,query.getCarefoProject());
            queryWrapper.like(StringUtils.isNotBlank(query.getCarefoPhoneNumber()),TCareforInfoDO::getCarefoPhoneNumber,query.getCarefoPhoneNumber());
        }

        return tCareforInfoMapper.selectPage(page,queryWrapper);
    }

    /**
     * 批量审核
     * @param careforIds
     * @param auditStatus
     */
    @Override
    @Transactional
    public void batchAudit(List<Integer> careforIds, Integer auditStatus) {
        if (CollectionUtils.isEmpty(careforIds)) {
            throw new TransitException("请选择要审核的数据");
        }
        if (ObjectUtils.isEmpty(auditStatus) ||
                !Arrays.stream(AuditStatusEnum.values()).map(AuditStatusEnum::getCode).collect(Collectors.toList()).contains(auditStatus)) {
            throw new TransitException("审核无效，请联系管理员");
        }

        List<TCareforInfoDO> tCareforInfoDOList = Lists.newArrayList();

      /*  // 获取要审核的数据信息
        LambdaQueryWrapper<TCareforInfoDO> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.in(TCareforInfoDO::getId,careforIds);
        queryWrapper.eq(TCareforInfoDO::getIsDelTag, BooleanEnum.NO.getCode());
        List<TCareforInfoDO> tCareforInfoDOListByIds = tCareforInfoMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(tCareforInfoDOListByIds)) {
            throw new TransitException("未获取到审核的数据");
        }

        // 校验是否存在不是待审核状态的数据
        List<TCareforInfoDO> filterList = tCareforInfoDOListByIds.
                stream().
                filter(item -> !Objects.equals(item.getAuditStatus(), AuditStatusEnum.RUNING.getCode())).
                collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(filterList)) {
            throw new TransitException("审核失败，存在已审核数据");
        }*/

        careforIds.forEach(item -> {
            TCareforInfoDO tCareforInfoDO = new TCareforInfoDO();
            tCareforInfoDO.setId(item);
            tCareforInfoDO.setAuditStatus(auditStatus);
            tCareforInfoDOList.add(tCareforInfoDO);
        });

        updateBatchById(tCareforInfoDOList);
    }

    @Override
    @Transactional
    public void saveCarefor(CareforRequest request) {
        boolean isTrue = tCarFleetManageService.checkImageUrl(request.getImageUrl());
        if (!isTrue) {
            throw new TransitException("图片上传有误");
        }
        User user = userService.getByPhone(request.getCarefoPhoneNumber());
        TCareforInfoDO tCareforInfoDO = new TCareforInfoDO();
        if(user==null){
            //注册新用户
            User user1 = new User();
            user1.setPhone(request.getCarefoPhoneNumber());
            user1.setStatus(true);
            user1.setRealName(request.getRealName());
            user1.setCardId(request.getCardId());
            if(request.getSex() != null){
                user1.setSex(request.getSex());
            }
            userService.save(user1);
            tCareforInfoDO.setAppUserId(user1.getUid());
        }else{
            //更新用户信息，phone，cardId，sex，realname
            user.setPhone(request.getCarefoPhoneNumber());
            user.setCardId(request.getCardId());
            if(request.getSex() != null){
                user.setSex(request.getSex());
            }
            user.setRealName(request.getRealName());
            userService.updateById(user);
            tCareforInfoDO.setAppUserId(user.getUid());
        }
        BeanUtil.copyProperties(request,tCareforInfoDO);
        save(tCareforInfoDO);
    }


}
